const axios = require("axios")
const Access_tokens = require("../models/Access_tokens")
const Reserves = require("../models/Reserves")

const reservejoin = async (req, res) => {
    console.log(req.body)

    const APP_ID = "wx9d08284632afafe2"
    const APP_SECRET = "44672f74531fad22be666f8e37c0a460"
    const APP_URL = 'https://api.weixin.qq.com/cgi-bin/token'
    const getTokenUrl = `${APP_URL}?appid=${APP_ID}&secret=${APP_SECRET}&grant_type=client_credential`

    var access_token = ""

    const Accesstokenfound = await Access_tokens.findOne()

    if (Accesstokenfound) {
        access_token = Accesstokenfound.token
    } else {
        const getaccess_token = await axios({
            url: getTokenUrl,
            method: "get"
        })
        access_token = getaccess_token.data.access_token
        await Access_tokens({ "token": access_token }).save()
    }

    let sendUrl = 'https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=' + access_token


 Reserves.findById(req.body.id_reserve).populate

    let tmpData = {
        "access_token": access_token,
        "touser": req.user.openid,
        "template_id": "3TJHgk7k7IHC0HAdTmfqKoK18epWKCOE2VlTTaR0NQU", // 信息模板id
        "page": "pages/index/index", // 指定点击提醒信息跳转到小程序的页面
        "miniprogram_state": "developer",
        "lang": "zh_CN",
        "data": {
            "phrase1": {
                "value": "预约成功"
            },
            "thing2": {
                "value": "这是预约门店"
            },
            "thing4": {
                "value": "这是预约剧本"
            },
            "time3": {
                "value": "2022-7-19 18:00:00"
            },
            "thing5": {
                "value": "请留意车队群聊通知并准时到场"
            },
        },
    }

    const sendRes = await axios({
        url: sendUrl,
        data: tmpData,
        method: "post"
    })
    console.log(sendRes.data)
    res.status(200)

}
module.exports = { reservejoin }